package com.oauth.global.client.ui.status;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class StatusTextArea extends Composite implements HasValue<String> {

	private static StatusTextAreaUiBinder uiBinder = GWT.create(StatusTextAreaUiBinder.class);

	interface StatusTextAreaUiBinder extends UiBinder<Widget, StatusTextArea> {
	}

	private String defaultText;

	/**
	 * @return the defaultText
	 */
	public String getDefaultText() {
		return defaultText;
	}

	/**
	 * @param pDefaultText
	 *            the defaultText to set
	 */
	public void setDefaultText(String pDefaultText) {
		defaultText = pDefaultText;
	}

	@UiField
	TextArea textArea;

	public StatusTextArea() {
		initWidget(uiBinder.createAndBindUi(this));
		textArea.setVisibleLines(2);
		textArea.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent pEvent) {
				String statusText = textArea.getText();
				if (statusText != null && statusText.equals(getDefaultText())) {
					textArea.setText("");
				}
			}

		});
		textArea.addBlurHandler(new BlurHandler() {

			@Override
			public void onBlur(BlurEvent pEvent) {
				String statusText = textArea.getText();
				if (isEmpty(statusText)) {
					textArea.setText(getDefaultText());
				}
			}

		});
	}

	public void setFocus(boolean focusable) {
		textArea.setFocus(focusable);
	}

	private boolean isEmpty(String pStatusText) {
		return pStatusText == null || pStatusText.trim().length() == 0;
	}

	@Override
	public String getValue() {
		return textArea.getText();
	}

	@Override
	public void setValue(String pValue) {
		textArea.setText(pValue);
	}

	@Override
	public void setValue(String pValue, boolean pFireEvents) {
		if (pFireEvents)
			ValueChangeEvent.fireIfNotEqual(textArea, getValue(), pValue);
		setValue(pValue);
	}

	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> pHandler) {
		return textArea.addValueChangeHandler(pHandler);
	}

}
